import React, { useState, useEffect } from 'react'
import { UdPageHeader, UdFilter, UdModal, http, uaaApp, columnRenders, validators } from '@/lib'
import { Table, Button, Select, Statistic } from 'antd'
import apis from '@/apis/CostManage';
import axios from 'axios';
import './index.scss';
import { downBlobFile } from '@/utils/methods'
import { WrappedFormUtils } from 'antd/lib/form/Form';
import UdSelect from '@/components/UdFormControls/UdSelect';
import { getBrandSelectList, getDealerListByBrand } from '@/common/Request';

//接口字段映射
const fieldMap = {
  /**
   * 表格一
   */

  //营销费用兑现方式
  type: "ExpenseWayCodeAndName",
  //费用总金额
  totalAmount: "Money",
  //已使用金额
  usedAmount: "UsedMoney",
  //转移金额
  transferAmount: "OutMoney",
  //调整金额
  adjustmentAmount: "AdjustMoney",
  //冻结金额
  frozenAmount: "FreezeMoney",
  //可用费用金额
  amountAvailable: "CanUseMoney",

  /**
   * 表格二
   */
  //报销单名称
  name: "AccountName",
  //报销单号
  no: "AccountNumber",
  //报销单年度
  year: "FiscalYearValue",
  //是否调入
  isTransfer: "BlTransferRequestItem",
  //是否冻结
  isFreeze: "BlFreezeMoney",
  //费用类型
  typesOfFee: "ExpenseTypeCode",
  //金额
  amount: "Money",


}


export default class List extends React.Component<any> {

  private filterForm: WrappedFormUtils

  state = {
    brands: [],
    showDetails: false,
    tableData: [],
    id: 0,
    isLoading: false,
    searchItems: {
      BrandCodes: undefined,
      dealerCode: undefined
    },
    dealerCodeOptions: [],
  }

  componentDidMount() {
    this.getBrandList()
  }

  private getBrandList = () => {
    getBrandSelectList().then(result => {
      this.setState({
        brands: result,
      })
    })
  }

  private getDealerListByBrand = (code) => {
    // 组织切换，重置经销商条件
    this.filterForm.setFieldsValue({ dealerCode: undefined })
    getDealerListByBrand(code).then(result => {
      this.setState({
        dealerCodeOptions: result,
      })
    })
  }

  getList = () => {
    this.setState({ isLoading: true })
    let BrandCodes = this.state.searchItems?.BrandCodes ? [this.state.searchItems?.BrandCodes] : undefined
    http.post(apis.getFundsListDetais, { page: 1, size: 100000, ...this.state.searchItems, BrandCodes }).then(res => {
      let data = {
        ExpenseWayCodeAndName: "总计",
        Money: res?.data?.sumMoney,
        UsedMoney: res?.data?.sumUsedMoney,
        AdjustMoney: res?.data?.sumAdjustMoney,
        FreezeMoney: res?.data?.sumFreezeMoney,
        CanUseMoney: res?.data?.sumCanUseMoney,
        OutMoney: res?.data?.sumOutMoney,
      }
      this.setState({ tableData: [...res?.data?.costList, data] })
    }).finally(() => {
      this.setState({ isLoading: false })
    })
  }

  private resetFilterHandle = () => {
    this.setState({
      tableData: [],
    })
  }

  render() {
    return <div className="cost-list-box">
      <UdPageHeader title="我的费用" />
      <UdFilter items={[
          {
            id: "BrandCodes", label: "销售组织", rules: [validators.required], render: <UdSelect onChange={this.getDealerListByBrand} options={this.state.brands} allowClear={false} />
          },
          {
            id: "dealerCode", label: "经销商", rules: [validators.required], render: <UdSelect options={this.state.dealerCodeOptions} showSearch={true} allowClear={false} />
          }
        ]}
        onSearch={(value) => {
          let searchItems = value
          this.setState({ searchItems }, () => { this.getList() })
        }}
        loading={this.state.isLoading}
        getForm={(form) => this.filterForm = form}
        resetAfter={this.resetFilterHandle}
      />
      <Table
        loading={this.state.isLoading}
        scroll={{ x: true }}
        rowKey={(record, index) => index + ""}
        dataSource={this.state.tableData}
        columns={[
          {
            dataIndex: 'SalesOrganizationName',
            title: "销售组织"
          },
          {
            dataIndex: fieldMap.type,
            title: "营销费用兑现方式"
          },
          {
            dataIndex: fieldMap.totalAmount,
            title: "费用总金额",
            align: 'right',
            render: (text) => (text || text == 0) && <Statistic value={text} precision={2} />
          },
          {
            dataIndex: fieldMap.usedAmount,
            title: "已使用金额",
            align: 'right',
            render: (text) => (text || text == 0) && <Statistic value={text} precision={2} />
          },
          {
            dataIndex: fieldMap.transferAmount,
            title: "转移金额",
            align: 'right',
            render: (text) => (text || text == 0) && <Statistic value={text} precision={2} />
          },
          {
            dataIndex: fieldMap.adjustmentAmount,
            title: "调整金额",
            align: 'right',
            render: (text) => (text || text == 0) && <Statistic value={text} precision={2} />
          },
          {
            dataIndex: fieldMap.frozenAmount,
            title: "冻结金额",
            align: 'right',
            render: (text) => (text || text == 0) && <Statistic value={text} precision={2} />
          },
          {
            dataIndex: fieldMap.amountAvailable,
            title: "可用费用金额",
            align: 'right',
            render: (text) => (text || text == 0) && <Statistic value={text} precision={2} />
          },
          {
            dataIndex: "dos",
            title: "操作",
            width: 90,
            render: columnRenders.operate([
              { title: '查看明细', show: (text, record) => record.ExpenseWayCodeAndName !== "总计", action: (text, record) => this.toDetail(record) }
            ])
          }
        ]}
        pagination={false}
      />
      <div style={{ height: "20px" }}></div>
      {
        // this.state.showDetails && <Details detailsProps={this.state.detailsProps} BrandCodes={this.state.searchItems.BrandCodes} propsId={this.state.id} />
      }
    </div>
  }

  public toDetail = (record) => {
    const { dealerCode } = this.state.searchItems
    this.props.history.push({
      pathname: `/cost-management/list/details/${record.ExpenseWayCode}/${this.state.searchItems.BrandCodes}`,
      search: `dealerCode=${dealerCode}`
    })
  }
}
